//
// Created by 崔世强 on 2018/4/25.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SnapKit
import Kingfisher
import Toast_Swift
import SwiftyJSON

class DeleteGroupMemberController: ChatBaseController {
    
    lazy var tableView: UITableView = {
        var table = UITableView()
        table.delegate = self
        table.dataSource = self
        table.separatorStyle = .singleLine
        table.isEditing = true
        table.allowsMultipleSelectionDuringEditing = true
        //        table.backgroundColor = .clear
        table.tableFooterView = UIView(frame: CGRect.zero)
        table.estimatedRowHeight = 50
        return table
    }()
    
    private let text = "确定"
    
    lazy var doneButtonItem: UIBarButtonItem = {
        let barItem = UIBarButtonItem(title: text, style: .plain, target: self, action: #selector(done))
        barItem.tintColor = kBtnGreen
        barItem.isEnabled = false
        return barItem
    }()
    
    var groupId:Int!
    var groupMembers:[ChatGroupMember] = [ChatGroupMember]()
    
    var selected = Set<Int>()
    
    let groupService = GroupService()
    let msgService = ChatService()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "删除成员"
        self.navigationItem.rightBarButtonItem = doneButtonItem
//        self.view.backgroundColor = .white
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
        
        do {
            let members = try groupService.getChatGroupMembers(groupId, limit: 100000)
            for groupMember in members {
                if !groupMember.me {
                    groupMembers.append(groupMember)
                }
            }
        }catch {
            print(error)
        }
        
    }
    
    fileprivate func onDelMemberSuccess() {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    fileprivate func onDelMemberFailure(_ msg: String) {
        DispatchQueue.main.async {
            self.view.hideModalToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    @objc func done() {
            print(selected)
            self.view.makeModalToastActivity(.center)
            let userIds = Array(self.selected)
            IM.request(.deleteGroupMembers(groupId: groupId, manageId: AppStatusManager.instance.userLoginStatus.1 ?? 0, userIds: userIds), success: { [unowned self] (json) in
                if reqSuccess(json["code"].stringValue) {
                    do {
                        try self.groupService.delete(self.groupId, members: userIds)
                    } catch {
                        print(error)
                    }
                    self.onDelMemberSuccess()
                } else {
                    let msg = json["msg"].stringValue
                    self.onDelMemberFailure(msg)
                }
                }, error: { (code) in
                    print("状态异常：\(code)")
                    self.onDelMemberFailure("服务异常，请稍后再试")
            }) { (error) in
                print(error)
                self.onDelMemberFailure("服务或网络异常")
            }
    }
}

extension DeleteGroupMemberController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMembers.count
    }
    
    //生成表视图单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let singleLine = "singleLine"
        var cell = tableView.dequeueReusableCell(withIdentifier: singleLine) as? SelectViewCell
        if cell == nil {
            cell = SelectViewCell(style: .default, reuseIdentifier: singleLine)
        }
        cell?.multipleSelectionBackgroundView = UIView()
        cell?.tintColor = kBtnGreen
        let groupMember = groupMembers[indexPath.row]
        cell!.nameLabel.text = groupMember.contact?.remarkName ?? groupMember.nickName ?? ""
        cell!.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(groupMember.contact?.avatar ?? "") ?? URL(string: "localhost")!), for: .normal, placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        return cell!
    }
}

extension DeleteGroupMemberController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let member = groupMembers[indexPath.row]
        self.selected.insert(member.userId)
        self.doneButtonItem.title = "\(text)(\(self.selected.count))"
        self.doneButtonItem.isEnabled = true
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath){
        let member = groupMembers[indexPath.row]
        self.selected.remove(member.userId)
        let numberText = self.selected.isEmpty ? "" : "(\(self.selected.count))"
        self.doneButtonItem.title = "\(text)\(numberText)"
        self.doneButtonItem.isEnabled = !self.selected.isEmpty
    }
    
    //将选中某行
    //    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    //        let cell = tableView.cellForRow(at: indexPath)
    //        return indexPath
    //    }
    
}
